// 配置Tailwind自定义颜色和字体
tailwind.config = {
    theme: {
        extend: {
            colors: {
                primary: '#165DFF',
                secondary: '#36CFC9',
                accent: '#722ED1',
                neutral: '#F5F7FA',
                dark: '#1D2129',
                success: '#52C41A',
                warning: '#FAAD14',
                danger: '#F5222D'
            },
            fontFamily: {
                inter: ['Inter', 'system-ui', 'sans-serif'],
            },
        }
    }
}

document.addEventListener('DOMContentLoaded', function() {
    // 验证用户登录状态
    const users = JSON.parse(localStorage.getItem('registeredUsers')) || [];
    const loginEmail = localStorage.getItem('currentLoginEmail');
    
    if (!loginEmail) {
        window.location.href = 'index.html';
        return;
    }
    
    // 获取当前用户信息
    const currentUser = users.find(user => user.email === loginEmail);
    if (currentUser) {
        // 更新导航栏用户信息
        document.getElementById('user-display-name').textContent = currentUser.name || '用户';
        if (currentUser.avatar) {
            document.getElementById('header-avatar').src = currentUser.avatar;
        }
    } else {
        localStorage.removeItem('currentLoginEmail');
        window.location.href = 'index.html';
    }
    
    // 移动端菜单切换
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const mobileMenu = document.getElementById('mobile-menu');
    
    mobileMenuButton.addEventListener('click', function() {
        mobileMenu.classList.toggle('hidden');
    });
    
    // 加载隐私设置
    function loadPrivacySettings() {
        const privacySettings = JSON.parse(localStorage.getItem('privacySettings')) || {
            anonymousAnalytics: true,
            shareTasks: true
        };
        
        document.getElementById('anonymous-analytics').checked = privacySettings.anonymousAnalytics;
        document.getElementById('share-tasks').checked = privacySettings.shareTasks;
    }
    
    // 保存隐私设置
    function savePrivacySettings() {
        const privacySettings = {
            anonymousAnalytics: document.getElementById('anonymous-analytics').checked,
            shareTasks: document.getElementById('share-tasks').checked
        };
        
        localStorage.setItem('privacySettings', JSON.stringify(privacySettings));
        showToast('隐私设置已保存');
    }
    
    // 监听隐私设置变化
    document.getElementById('anonymous-analytics').addEventListener('change', savePrivacySettings);
    document.getElementById('share-tasks').addEventListener('change', savePrivacySettings);
    
    // 导出数据
    document.getElementById('export-data').addEventListener('click', function() {
        if (currentUser) {
            // 准备要导出的数据
            const exportData = {
                user: {
                    name: currentUser.name,
                    email: currentUser.email,
                    nickname: currentUser.nickname,
                    phone: currentUser.phone,
                    bio: currentUser.bio,
                    createdAt: currentUser.createdAt
                },
                tasks: JSON.parse(localStorage.getItem('userTasks')) || []
            };
            
            // 创建JSON文件并下载
            const dataStr = JSON.stringify(exportData, null, 2);
            const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
            
            const exportFileDefaultName = `userhub-data-${new Date().toISOString().slice(0,10)}.json`;
            
            const linkElement = document.createElement('a');
            linkElement.setAttribute('href', dataUri);
            linkElement.setAttribute('download', exportFileDefaultName);
            linkElement.click();
            
            showToast('数据导出成功');
        }
    });
    
    // 删除账户相关
    document.getElementById('delete-account').addEventListener('click', function() {
        document.getElementById('delete-account-modal').classList.remove('hidden');
    });
    
    document.querySelectorAll('.cancel-modal').forEach(button => {
        button.addEventListener('click', function() {
            document.getElementById('delete-account-modal').classList.add('hidden');
        });
    });
    
    document.getElementById('delete-account-modal').addEventListener('click', function(e) {
        if (e.target === this) {
            this.classList.add('hidden');
        }
    });
    
    document.getElementById('confirm-account-deletion').addEventListener('click', function() {
        const confirmText = document.getElementById('confirm-delete-text').value;
        
        if (confirmText !== 'DELETE') {
            alert('请输入"DELETE"确认删除');
            return;
        }
        
        // 从用户列表中删除
        const updatedUsers = users.filter(u => u.email !== loginEmail);
        localStorage.setItem('registeredUsers', JSON.stringify(updatedUsers));
        
        // 清除本地存储的任务数据
        localStorage.removeItem('userTasks');
        
        // 清除登录状态
        localStorage.removeItem('currentLoginEmail');
        
        // 跳转到登录页
        window.location.href = 'index.html';
    });
    
    // 退出登录
    document.getElementById('logout-btn').addEventListener('click', function() {
        if (confirm('确定要退出登录吗？')) {
            localStorage.removeItem('currentLoginEmail');
            window.location.href = 'index.html';
        }
    });
    
    // 显示提示消息
    function showToast(message) {
        const toast = document.getElementById('success-toast');
        document.getElementById('toast-message').textContent = message;
        
        // 显示toast
        toast.classList.remove('translate-y-20', 'opacity-0');
        toast.classList.add('translate-y-0', 'opacity-100');
        
        // 3秒后隐藏
        setTimeout(() => {
            toast.classList.remove('translate-y-0', 'opacity-100');
            toast.classList.add('translate-y-20', 'opacity-0');
        }, 3000);
    }
    
    // 页面加载时执行
    loadPrivacySettings();
      // 用户菜单下拉功能
            const userMenuButton = document.getElementById('user-menu-button');
            const userMenuDropdown = document.getElementById('user-menu-dropdown');
            
            // 点击头像切换菜单显示/隐藏
            userMenuButton.addEventListener('click', function(event) {
                event.stopPropagation(); // 防止事件冒泡
                userMenuDropdown.classList.toggle('hidden');
            });
            
            // 点击页面其他地方关闭菜单
            document.addEventListener('click', function(event) {
                if (!userMenuButton.contains(event.target) && !userMenuDropdown.contains(event.target)) {
                    userMenuDropdown.classList.add('hidden');
                }
            });
            
            // 退出登录功能
            document.getElementById('logout-button').addEventListener('click', function() {
                localStorage.removeItem('currentLoginEmail');
                window.location.href = 'index.html';
            });
            
     updateAvatar();
    
    // 监听头像更新事件
    window.addEventListener('avatarUpdated', function(e) {
        const headerAvatar = document.getElementById('header-avatar');
        if (headerAvatar) {
            headerAvatar.src = e.detail.avatar;
        }
    });
    
    // 监听本地存储变化（应对多标签页情况）
    window.addEventListener('storage', function(e) {
        if (e.key === 'registeredUsers') {
            updateAvatar();
        }
    });
});

// 移除错误的登录状态清除代码
const currentUser = localStorage.getItem('currentLoginEmail');
// 只有在用户登录状态存在时才处理任务数据
if (currentUser) {
    const storageKey = `userTasks_${currentUser}`;
    
    // 读取任务数据
    let tasks = JSON.parse(localStorage.getItem(storageKey)) || [];
    
    // 保存任务数据的函数（需要时调用）
    function saveTasks() {
        localStorage.setItem(storageKey, JSON.stringify(tasks));
    }
}
